package cn.fastoo.filter;

import cn.fastoo.common.dao.UserAccountDao;
import cn.fastoo.common.entity.UserAccount;
import cn.fastoo.common.sampleframe.dto.JsonResult;
import cn.fastoo.common.sampleframe.search.Search;
import cn.fastoo.utils.HttpRequestUtils;
import cn.fastoo.utils.ResponseTypeOutUtils;
import com.alibaba.dubbo.common.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Map;

public class ApiFilter implements Filter {
	
	private UserAccountDao userAccountDao;
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
 		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		UserAccount userAccount = null;

		String apiKey = request.getParameter("apiKey");
		if(StringUtils.isNotBlank(apiKey)){
			userAccount = userAccountDao.findOne(new Search().addSearchFilter("EQ_apiKey",apiKey));
		}

		if(userAccount!=null){
			request.setAttribute("userAccount",userAccount);
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}

		if(userAccount==null){
			ResponseTypeOutUtils.renderText(response, JsonResult.create(101,"不存在此用户"));;
		}

		return;
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ServletContext sc = filterConfig.getServletContext();
		WebApplicationContext wac = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		userAccountDao = (UserAccountDao) wac.getBean("userAccountDao");
	}

	@Override
	public void destroy() {}

}
